import { ReactElement, useState, useEffect } from 'react'
import { Modal, Button, Table, TablePaginationConfig } from 'antd'
import { getColumn } from './util'
import { InputBatchSchema } from '@components/schema/inputBatch'
import { getListRequest } from './ajax'
import { awaitWrap } from '@js/tool'
import { useDispatch } from 'react-redux'

async function getList (page: number | undefined, limit: number | undefined, setDataSource: (v: InputBatchSchema[]) => void, setLoading: (v: boolean) => void, setCurrent: (v: number) => void, setPageSize: (v: number) => void, setTotal: (v: number) => void): Promise<void> {
  setLoading(true)
  if (page === undefined) {
    page = 1
  }
  if (limit === undefined) {
    limit = 10
  }
  const [e, d] = await awaitWrap(getListRequest(page, limit))
  setCurrent(page)
  setPageSize(limit)
  setLoading(false)
  if (e === null && d !== null) {
    setDataSource(d.list)
    setTotal(d.total)
  }
}

interface Props {
  visible: boolean
  hide: () => void
}

function Main ({ visible, hide }: Props): ReactElement {
  const dispatch = useDispatch()
  const [total, setTotal] = useState(0)
  const [current, setCurrent] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [dataSource, setDataSource] = useState<InputBatchSchema[]>([])
  const [loading, setLoading] = useState(false)
  const pagination: TablePaginationConfig = {
    total,
    current,
    pageSize,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number) => `合计 ${total} 条`,
    size: 'small'
  }
  function initData (): void { getList(current, pageSize, setDataSource, setLoading, setCurrent, setPageSize, setTotal).catch(e => console.error(e)) }
  useEffect(() => {
    if (visible) {
      initData()
    }
  }, [visible])
  return (
    <Modal title='导入历史' visible={visible} width={900} onCancel={hide} footer={<Button onClick={hide}>返回</Button>}>
      <Table rowKey='id' columns={getColumn(dispatch, hide)} loading={loading} dataSource={dataSource} pagination={pagination} onChange={async (d) => {
        await getList(d.current, d.pageSize, setDataSource, setLoading, setCurrent, setPageSize, setTotal)
      }} />
    </Modal>
  )
}

export default Main
